<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class M_library_books extends MY_Model {
	
	protected $_table = "library_books";
	protected $_uid = "book_id";

	public function __construct(){
		parent::__construct();
		$this->_timestamp = false;
	}	

	/**
	 * Upload from Uploaded CSV file
	 * @path path of the csv file
	 */
	public function upload_from_csv($path)
	{
		$this->load->helper('file');
		$this->load->model('M_media_types','m_type');
		$this->load->model('M_library_book_category','m_cat');

		$sly = new stdClass;
		$sly->status = false;

		$string = trim(read_file($path)); // READ and Extract String from the file
		$arr_str = explode("\n", $string); // Explode the string per line and save to array
		// vd($arr_str);
		/**  LOOP ARRAY STRING AND SAVE DATA ***/
			if($arr_str){

				$ctr_media_s = 0;
				$ctr_media_e = 0;

				foreach ($arr_str as $key => $l) {
					
					if($key == 0){ continue; } //EXCLUDE THE FIRST, CONTAINS THE HEADER FILE
					if(!trim($l)){ continue; }

					$ara = explode(',', $l); // EXTRACT BY COMMA

					/* FORMAT
					$fields[0][0] = 'Media Type';
					$fields[0][1] = 'Media Subject';
					$fields[0][2] = 'Media Accession Number';
					$fields[0][3] = 'Media Call Number';
					$fields[0][4] = 'Media Title';
					$fields[0][5] = 'Media Description';
					$fields[0][6] = 'Number of Copies (Integer)';	
					$fields[0][7] = 'Media ISBN';
					$fields[0][8] = 'Media Author';	
					$fields[0][9] = 'Media Publisher';	
					$fields[0][10] = 'Date Publish (yyyy-mm-dd)';
					$fields[0][11] = 'Barcode';*/

					unset($data);
					$book_type = isset($ara[0]) ? trim($ara[0]) : '';
					$book_category = isset($ara[1]) ? trim($ara[1]) : '';
					$data['accession_number'] = isset($ara[2]) ? trim($ara[2]) : '';
					$data['call_number'] = isset($ara[3]) ? trim($ara[3]) : '';
					$data['book_name'] = $book_name = isset($ara[4]) ? trim($ara[4]) : '';
					$data['book_desc'] = $book_desc = isset($ara[5]) ? trim($ara[5]) : '';
					$data['book_copies'] = $book_copies = isset($ara[6]) ? intval(trim($ara[6])) : '';
					$data['book_isbn'] = $book_isbn = isset($ara[7]) ? trim($ara[7]) : '';
					$data['book_author'] = $book_author = isset($ara[8]) ? trim($ara[8]) : '';
					$data['book_publisher'] = $book_publisher = isset($ara[9]) ? trim($ara[9]) : '';
					$data['book_dop'] = $book_dop = isset($ara[10]) ? date('Y-m-d',strtotime(trim($ara[10]))) : '';
					$data['book_barcode'] = $book_barcode = isset($ara[11]) ? trim($ara[11]) : '';
					$data['book_created'] = NOW;
					$data['book_updated'] = NOW;
					
					if($book_name !== "" && $book_desc !== "" && $book_copies > 0){

						/** GET BOOK TYPE
						 ** If Book type is in the database get the id if not create first
						 **/
							$typ = $this->m_type->pull(array('media_type'=>$book_type));
							if($typ){
								$data['media_type_id'] = $typ->id;
							}else{
								//create media type
								unset($med_type);
								$media_type['media_type'] = $book_type;
								$rs_med = (object)$this->m_type->insert($media_type);
								if($rs_med){
									$data['media_type_id'] = $rs_med->id;
								}
							}

						/** GET BOOK CATEGORY
						 ** If Book category is in the database get the id if not create first
						 **/
							$cat = $this->m_cat->pull(array('lbc_name'=>$book_category));
							if($cat){
								$data['book_category'] = $cat->id;
							}else{
								//create media category
								unset($category);
								$category['lbc_name'] = $book_category;
								$category['lbc_desc'] = $book_category;
								// $this->m_cat->_timestamp = false;
								$rs_cat = (object)$this->m_cat->insert($category);
								if($rs_cat){
									$data['book_category'] = $rs_cat->id;
								}
							}
						
						/** UPLOADS **/

						$rs_up = $this->insert($data);

						if($rs_up){
							$ctr_media_s++;
						}else{
							$ctr_media_e++;
						}
					}
					else
					{
						$ctr_media_e++;
					}
				}

				if($ctr_media_s > 0){
					$sly->msg = "Media upload successfull. There are $ctr_media_s item/s has been added to your database.";
					if($ctr_media_e > 0){
						$sly->msg .=" $ctr_media_e item/s failed.";
					}

					$sly->status = true;
					$sly->media_upload_success = $ctr_media_s;
					$sly->media_upload_error = $ctr_media_e;
					return $sly;
				}
			}

		$sly->msg = "No media has been upload, please follow the format given and try again";
		return $sly;
	}

	/**
	 * Get master list by type
	 * get all media type with its corresponding media count and data
	 * @return Obj
	 */
	public function get_master_list_by_type($id = false)
	{
		$this->load->model('M_media_types','m_type');

		$sly = false;

		unset($get);
		if($id){
			$get['where']['id'] = $id;
		}
		$get['fields'] = 'id, media_type';
		$get['order'] = 'media_type';
		$type = $this->m_type->get_record(false, $get); // get type
		
		if($type){

			foreach ($type as $kt => $t) {
				
				/** GET ALL MEDIA WITH THIS TYPES **/
				unset($get);
				$get['where']['media_type_id'] = $t->id;
				$get['order'] = 'book_name';
				$get['fields'] = array(
						'library_books.*',
						'library_book_category.lbc_name as category',
						'book_copies - book_borrowed as available',
						'media_types.media_type',
				);

				$get['join'][] = array(
						'table' => 'media_types',
						'on' => 'library_books.media_type_id = media_types.id',
						'type' => 'left'
					);

				$get['join'][] = array(
						'table' => 'library_book_category',
						'on' => 'library_books.book_category = library_book_category.lbc_id',
						'type' => 'left'
					);
				$rs = $this->get_record(false, $get);
				$sly[] = array(
						'head' => $t, // type
						'tail' => $rs, // media of that type
					);
			}
		}
		
		return $sly;		
	}

	/**
	 * Get master list by category
	 * get all media category with its corresponding media count and data
	 * @return Obj
	 */
	public function get_master_list_by_category($id = false)
	{
		$this->load->model('M_library_book_category','m_cat');

		$sly = false;

		unset($get);
		if($id){
			$get['where']['lbc_id'] = $id;
		}
		$get['fields'] = 'lbc_id as id, lbc_name';

		$get['order'] = 'lbc_name';

		$cat = $this->m_cat->get_record(false, $get); // get category
		
		if($cat){

			foreach ($cat as $kt => $t) {
				
				/** GET ALL MEDIA WITH THIS category **/
				unset($get);
				$get['where']['book_category'] = $t->id;
				$get['order'] = 'book_name';
				$get['fields'] = array(
						'library_books.*',
						'library_book_category.lbc_name as category',
						'book_copies - book_borrowed as available',
						'media_types.media_type',
				);

				$get['join'][] = array(
						'table' => 'media_types',
						'on' => 'library_books.media_type_id = media_types.id',
						'type' => 'left'
					);

				$get['join'][] = array(
						'table' => 'library_book_category',
						'on' => 'library_books.book_category = library_book_category.lbc_id',
						'type' => 'left'
					);
				$rs = $this->get_record(false, $get);
				$sly[] = array(
						'head' => $t, // type
						'tail' => $rs, // media of that type
					);
			}
		}
		
		return $sly;		
	}
}